package io.flash.rpc.protocol;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * ===========================================================================
 * |  数据包长度(4 字节)  |  命令字(1 字节)   |   数据包内容(`数据包长度内容`个字节)  |
 * ===========================================================================
 */


public class PacketCodec extends ByteToMessageCodec<Object> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        byte[] bytes = JSON.toJSONString(o).getBytes(StandardCharsets.UTF_8);

        byteBuf.writeInt(1 + bytes.length);
        byteBuf.writeByte(CommandPacketClass.getCommand(o.getClass()));
        byteBuf.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        byteBuf.skipBytes(4);
        byte command = byteBuf.readByte();
        byte[] bytes = readBytes(byteBuf);
        list.add(JSON.parseObject(new String(bytes, StandardCharsets.UTF_8), CommandPacketClass.getPacketClass(command)));

    }

    private byte[] readBytes(ByteBuf byteBuf) {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);

        return bytes;
    }
}
